package com.free.mini.common.log;

import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class SensitiveDataConverter extends MessageConverter {


    @Override
    public String convert(ILoggingEvent event) {
        try {
            return doTuoMin(event);
        } catch (Exception e) {
            return super.convert(event);
        }
    }

    private String doTuoMin(ILoggingEvent event) {
        try {
            if (null == event.getArgumentArray()) {
                return event.getMessage();
            }
            String message = event.getMessage();
            String formattedMessage = event.getFormattedMessage();
            if (StringUtils.isBlank(message) && StringUtils.isBlank(formattedMessage)){
                return super.convert(event);
            }
            if(!DataMaskFilter.containKeyWord(message) && !DataMaskFilter.containKeyWord(formattedMessage)){
                return super.convert(event);
            }

            Object[] objects = Stream.of(
                    event.getArgumentArray()).map(obj -> {
                String msg;
                if (obj instanceof String) {
                    msg = obj.toString();
                    if (StringUtils.isNotBlank(msg)) {
                        try {
                            if (msg.startsWith("{")){
                                JSONObject jsonObject = JSONObject.parseObject(msg);
                                msg = JSON.toJSONString(jsonObject, DataMaskFilter.instance());
                                return msg;
                            }else if (msg.startsWith("[")){
                                JSONArray jsonArray = JSONArray.parseArray(msg);
                                msg = JSON.toJSONString(jsonArray, DataMaskFilter.instance());
                                return msg;
                            }

                        } catch (Exception e) {
                            msg = obj.toString();
                        }
                    }
                    if (StringUtils.isNotBlank(msg)) {
                        msg = DataMaskFilter.deSensitiveData(message,msg);
                    }

                } else {
                    // 其他类型 通过 fastjson Filter 功能脱敏后转成 json 字符串
                    msg = JSON.toJSONString(obj, DataMaskFilter.instance());
                }
                return msg;
            }).toArray();
            return MessageFormatter.arrayFormat(event.getMessage(), objects).getMessage();
        } catch (Exception e) {
            return event.getMessage();
        }
    }

}
